package shop.up;

import java.util.concurrent.*;

/**
 * CompletableFuture 异步编排 {@link CompletableFutureDemo1}
 *  - 并行化
 * @author Kevin
 * @date 2022/7/12
 */
public class CompletableFutureDemo1 {

    public static void main(String[] args) {
        // 创建线程池
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
                50,
                500,
                30, TimeUnit.SECONDS,
                new ArrayBlockingQueue<>(10000));

        // 线程1执行返回的结果：hello
        CompletableFuture<String> futureA = CompletableFuture.supplyAsync(() -> "hello");

        // 线程2获取到线程1执行的结果
        CompletableFuture<Void> futureB = futureA.thenAcceptAsync((s) -> {
            delaySec(3);
            printCurrTime(s+" 第一个线程");
        }, threadPoolExecutor);

        // 线程3获取到线程1执行的结果
        CompletableFuture<Void> futureC = futureA.thenAcceptAsync((s) -> {
            delaySec(1);
            printCurrTime(s+" 第二个线程");
        }, threadPoolExecutor);
    }

    private static void printCurrTime(String str) {
        System.out.println(str);
    }

    private static void delaySec(int i) {
        try {
            Thread.sleep(i*1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
